<template>
    <!--  外框架-->
    <div class="framework1">
        <!--      内框架-->
        <div class="framework2">
            <div class="top-class-table">
                <div class="header">
                    <div style="margin-left: 10px;font-weight: bold">菜单管理->部门菜单</div>
                </div>
                <!--      按钮行-->
                <div class="button_group">
                    <el-select
                        v-if="loginUserInfo.unitId === 1 && (loginUserInfo.responsibleScope === '5' || loginUserInfo.responsibleScope === '4')"
                        clearable class="selectedUnit-style" v-model="selectedUnit" @change="getRoleData"
                        placeholder="请选择部门">
                        <el-option v-for="item in unitData" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </div>
                <div style="height: calc(100vh - 134px)">
                    <el-table :data="tableData" :row-style="{ height: '47px' }"
                        style="width: 100%;height:calc(100% - 68px)" :header-cell-style="{ background: '#f4f3f9' }">
                        <el-table-column align="center" prop="unitName" label="所属部门" width="auto" />
                        <el-table-column align="center" prop="roleName" label="角色名称" width="auto" />
                        <el-table-column align="center" label="操作" width="200" v-if="permissionIsShow.edit">
                            <template v-slot="scope">
                                <el-button type="primary" size="small" icon="Edit"
                                    @click="editMenu(scope.row)">编辑菜单</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!--        页数导航栏-->
                    <div class="footer">
                        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                            :current-page="currentPage" :page-sizes="[10, 20,]" :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper" :total="total">
                        </el-pagination>
                    </div>
                </div>
            </div>

        </div>
        <!-- 编辑弹窗-->
        <el-dialog v-model="editVisible" :close-on-click-modal="false" title="编辑" width="600px" @close="cancelEdit()">
            <div v-loading="editLoading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)">
                <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
                    <el-form-item label="所属部门" prop="unitName">
                        <div style="color: #000000;  padding:0px 10px; ">
                            {{ editForm.unitName }}
                        </div>
                    </el-form-item>
                    <el-form-item label="角色名称" prop="roleName">
                        <div style="color: #000000;  padding:0px 10px; ">
                            {{ editForm.roleName }}
                        </div>
                    </el-form-item>
                    <el-form-item label="菜单权限" prop="menuIds">
                        <div>
                            <div v-for="(node, index) in rootNodes" :key="node.uuid" class="tree-wrapper">
                                <el-tree :ref="el => { if (el) editTreeRefs[index] = el }" :data="[node]" show-checkbox
                                    check-strictly node-key="uuid" highlight-current :props="defaultProps"
                                    @check-change="handleNodeChecked" />
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
                <div style="text-align: right; margin-top: 20px;">
                    <el-button @click="cancelEdit()">取消</el-button>
                    <el-button type="primary" @click="submitEditForm()">确定</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import request from "../../utils/request.js";


export default {
    data() {
        return {
            // 编辑弹窗
            editVisible: false,
            // 搜索条件
            searchName: '', //搜索名字
            selectedUnit: '', // 选中的单位ID

            unitData: [],
            tableData: [],
            currentPage: 1, //页码
            pageSize: 10, //页长
            total: 0,  //总表长

            // 菜单相关数据
            menuOperations: [],
            permissionData: [],
            editTreeRefs: [], // 编辑表单的树引用
            defaultProps: {
                children: 'menuDtos',
                label: 'name',
                value: 'uuid'
            },

            // 编辑表单
            editForm: {
                id: '',
                unitId: '',
                unitName: '',
                roleName: '',
                menuIds: [],
                permissionIds: [],
            },
            editFormRules: {

            },

            // 加载状态
            editLoading: false, // 编辑弹窗数据加载状态
            // 登录用户信息
            loginUserInfo: {
                id: '',
                responsibleScope: '', //查询范围
                roleLevel: '', //角色等级
                unitId: '', //内设部门ID
                userRole: '', //角色ID
                permissions: [], // 按钮路径（数据库中的path）
            },
            // 按钮权限
            permissionIsShow: {
                edit: false,
            }
        }

    },
    created() {
        const info = JSON.parse(localStorage.getItem("user"));
        this.loginUserInfo = {
            id: Number(info.id),
            responsibleScope: info.responsibleScope,
            roleLevel: Number(info.roleLevel),
            unitId: Number(info.unitId),
            userRole: Number(info.userRole),
            permissions: info.permissions.filter(item => Number(item.menuId) === 26).map(item => item.path),
        }
        this.permissionIsShow = {
            edit: this.loginUserInfo.permissions.includes('roleMenu-edit'),
        }
        this.load()
    },
    computed: {
        // 根节点列表
        rootNodes() {
            return this.menuOperations;
        }
    },
    methods: {
        load() {
            this.getUnitData()
            this.getRoleData()
            this.getMenuAllPermission()
        },
        // 格式化空值
        formatEmptyValue(row, column, cellValue) {
            // 为空、undefined、null或空字符串时显示 "-"
            if (cellValue === undefined || cellValue === null || cellValue === '') {
                return '-';
            }
            return cellValue;
        },
        getRoleData() {
            const responsibleScope = this.loginUserInfo.responsibleScope
            if (responsibleScope === '5') {
                // 所有部门的所有数据
                request.get("/role/getRolePage", {
                    params: {
                        pageNum: this.currentPage,
                        pageSize: this.pageSize,
                        unitId: this.selectedUnit,
                        roleLevel: this.loginUserInfo.roleLevel,
                    }
                }).then(res => {
                    if (res.code === '200') {
                        this.tableData = res.data.records
                        this.total = res.data.total
                    } else {
                        console.log("错误:" + res.msg)
                    }
                })
            } else if (responsibleScope === '4') {
                // 负责部门的所有数据
                request.get("/role/getRolePage", {
                    params: {
                        pageNum: this.currentPage,
                        pageSize: this.pageSize,
                        unitId: this.selectedUnit,
                        userId: this.loginUserInfo.id,
                        roleLevel: this.loginUserInfo.roleLevel,
                    }
                }).then(res => {
                    if (res.code === '200') {
                        this.tableData = res.data.records
                        this.total = res.data.total
                    } else {
                        console.log("错误:" + res.msg)
                    }
                })
            } else if (responsibleScope === '3' || responsibleScope === '2') {
                // 所在部门的所有数据
                request.get("/role/getRolePage", {
                    params: {
                        pageNum: this.currentPage,
                        pageSize: this.pageSize,
                        unitId: this.loginUserInfo.unitId,
                        roleLevel: this.loginUserInfo.roleLevel,
                    }
                }).then(res => {
                    if (res.code === '200') {
                        this.tableData = res.data.records
                        this.total = res.data.total
                    } else {
                        console.log("错误:" + res.msg)
                    }
                })
            } else {
                this.tableData = []
                this.total = 0
            }
        },
        getUnitData() {
            const responsibleScope = this.loginUserInfo.responsibleScope
            if (responsibleScope === '5') {
                // 所有部门
                request.get('/unit/all').then(res => {
                    if (res.code === '200') {
                        this.unitData = res.data;
                    }
                })

            } else if (responsibleScope === '4') {
                // 部分部门
                request.get('/unit/responsibleAll', {
                    params: {
                        userId: this.loginUserInfo.id,
                    }
                }).then(res => {
                    if (res.code === '200') {
                        this.unitData = res.data;
                    }
                })
            } else {
                this.unitData = [];
            }
        },
        // 获取所有页面的权限按钮
        async getMenuAllPermission() {
            await request.get("/permission/getMenuAllPermission").then(res => {
                if (res.code === '200') {
                    /**
                     *  res.data 是一个对象，key是菜单id，value是一个数组，数组中的每个元素是一个对象，对象包含菜单（key）的所有权限信息  
                     */
                    let permissionMap = res.data
                    // 遍历每一个key，将每一个key的value（一个数组）的所有permission添加uuid字段
                    for (let key in permissionMap) {
                        let permissionArray = permissionMap[key]
                        // // 过滤掉登录角色没有的权限
                        const info = JSON.parse(localStorage.getItem("user")) || {};
                        const loginPermission = info.permissions.map(item => item.id) || [];
                        permissionArray = permissionArray.filter(item => loginPermission.includes(item.id))
                        permissionArray.forEach(item => {
                            // 生成uuid字段
                            item.uuid = "permission_" + item.id
                            // 添加数据类型字段(用于判断是菜单还是按钮)
                            item.dataType = 'permission'
                        })
                        permissionMap[key] = permissionArray
                    }
                    this.permissionData = res.data
                }
            })

        },
        // 获取所有菜单
        async getAllMenuOperations(unitId) {
            await request.get("/unit-menu/getUnitMaxMenu", {
                params: {
                    unitId: unitId,
                }
            }).then(res => {
                if (res.code === '200') {
                    res.data.forEach(item => {
                        // 生成uuid字段
                        item.uuid = "menu_" + item.id
                        // 添加数据类型字段(用于判断是菜单还是按钮)
                        item.dataType = 'menu'
                        // 显示的名字
                        item.name = item.menuName
                        // 处理子菜单
                        if (item.menuDtos && item.menuDtos.length > 0) {
                            item.menuDtos.forEach(child => {
                                child.uuid = "menu_" + child.id
                                child.dataType = 'menu'
                                child.name = child.menuName
                                // 添加按钮权限
                                let buttonPermission = this.permissionData[`${child.id}`]
                                if (buttonPermission) {
                                    child.menuDtos = buttonPermission
                                }
                            })
                        }
                    })
                    this.menuOperations = res.data;
                }
            })

        },
        // 获取当前角色菜单
        async getRoleMenu(unitId, roleId) {
            let menuIds = []
            await request.get("/role-menu/getUnitAndRoleMenu", {
                params: {
                    unitId: unitId,
                    roleId: roleId,
                }
            }).then(res => {
                if (res.code === '200') {
                    menuIds = res.data || []
                }
            })
            return menuIds
        },
        // 获取当前角色已有的按钮权限
        async getRolePermission(roleId) {
            let permission = []
            await request.get("/role-permission/getPermissionIdByRoleId", {
                params: {
                    roleId: roleId,
                }
            }).then(res => {
                if (res.code === '200') {
                    permission = res.data || []
                }
            })
            return permission
        },

        // 编辑处理
        async editMenu(row) {
            this.editLoading = true
            this.editVisible = true;
            this.editForm = {
                id: row.id,
                unitId: row.unitId,
                unitName: row.unitName,
                roleName: row.roleName,
                menuIds: [],
                permissionIds: [],
            }
            // 获取单位最大菜单
            await this.getAllMenuOperations(row.unitId)

            let allId = []
            // 获取当前角色已有菜单ID
            this.editForm.menuIds = await this.getRoleMenu(row.unitId, row.id)
            // 获取当前角色已有的按钮权限ID
            this.editForm.permissionIds = await this.getRolePermission(row.id)

            // 合并并设置数节点的选中状态
            this.editForm.menuIds.forEach(item => {
                allId.push('menu_' + item)
            })
            this.editForm.permissionIds.forEach(item => {
                allId.push('permission_' + item)
            })

            this.$nextTick(() => {

                // 设置已选中的菜单
                this.editTreeRefs.forEach(tree => {
                    if (tree) {
                        tree.setCheckedKeys(allId);
                    }
                });

            });
            this.editLoading = false
        },
        // 提交编辑表单
        submitEditForm() {
            const params = {
                unitId: this.editForm.unitId,
                roleId: this.editForm.id,
                menuIds: this.editForm.menuIds,
                permissionIds: this.editForm.permissionIds,
            }
            request.post("/role-menu/editRoleMenu", params).then(res => {
                if (res.code === '200' && res.data === true) {
                    this.$message({
                        message: '更新成功',
                        type: 'success'
                    });
                    this.editVisible = false;
                    this.resetEditForm();
                    this.getRoleData();
                } else {
                    this.$message({
                        message: '更新失败',
                        type: 'error'
                    });
                    this.editVisible = false;
                    this.resetEditForm();
                    this.getRoleData();
                }
            })
        },
        // 取消编辑
        cancelEdit() {
            this.editVisible = false;
            this.resetEditForm();
        },
        // 重置编辑表单
        resetEditForm() {
            if (this.$refs.editFormRef) {
                this.$refs.editFormRef.resetFields();
            }
        },
        // 分页处理
        handleSizeChange(val) {
            this.pageSize = val;
            this.getRoleData();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.getRoleData();
        },

        // 处理节点选中事件
        handleNodeChecked(data, checked) {
            // 参数：传递给 data 属性的数组中该节点所对应的对象、节点本身是否被选中
            if (checked) {
                if (data.dataType === 'menu') {
                    // 如果数组里有，就不添加了
                    if (this.editForm.menuIds.includes(data.id)) {
                        return
                    } else {
                        this.editForm.menuIds.push(data.id);
                    }
                } else if (data.dataType === 'permission') {
                    // 如果数组里有，就不添加了
                    if (this.editForm.permissionIds.includes(data.id)) {
                        return
                    } else {
                        this.editForm.permissionIds.push(data.id);
                    }
                }
            } else {
                // 如果取消选中，从数组中移除
                if (data.dataType === 'menu') {
                    const index = this.editForm.menuIds.indexOf(data.id);
                    if (index !== -1) {
                        this.editForm.menuIds.splice(index, 1);
                    }
                } else if (data.dataType === 'permission') {
                    const index = this.editForm.permissionIds.indexOf(data.id);
                    if (index !== -1) {
                        this.editForm.permissionIds.splice(index, 1);
                    }
                }
            }
        },
    }
}
</script>

<style scoped>
#roleSpan {
    color: black;
    text-decoration: none;
}

/*   外框架   */
.framework1 {
    height: calc(100vh - 88px);
    width: calc(100vh - 200px);
    margin-left: 8px;
    border: solid 1px #D3D3D3;
}

/*   内框架   */
.framework2 {
    height: calc(100vh - 92px);
    border: solid 1px #D3D3D3;
}

/*   表格大标题   */
.header {
    font-size: 16px;
    font-weight: bold;
    padding: 4px 20px;
    background-color: #D3D3D3;
}

/*   表格按键组   */
.button_group {
    display: flex;
    padding: 4px 10px;
    background-color: #DDDDDD;
}

/*   表格分页处   */
.footer {
    padding: 4px 10px;
    background-color: #f4f3f9;
}

.el-dialog-image {
    height: 100px;
    width: 200px;
    margin-top: 10px;
    margin-right: 10px;
    border: 1px solid #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>
